<?php
header('Content-Type: application/json');

try {
    if (!isset($_FILES['image'])) {
        throw new Exception('没有上传文件');
    }

    $file = $_FILES['image'];
    if ($file['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('文件上传失败');
    }

    // 检查文件类型
    $allowed = ['image/jpeg', 'image/png', 'image/gif'];
    if (!in_array($file['type'], $allowed)) {
        throw new Exception('只允许上传 JPG、PNG 或 GIF 格式的图片');
    }

    // 创建上传目录
    $uploadDir = '../../uploads/heroes/';
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    // 生成唯一文件名
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = uniqid() . '.' . $ext;
    $filepath = $uploadDir . $filename;

    // 移动文件
    if (!move_uploaded_file($file['tmp_name'], $filepath)) {
        throw new Exception('文件保存失败');
    }

    // 返回相对路径
    echo json_encode([
        'success' => true,
        'url' => '/admin/uploads/heroes/' . $filename
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?> 